package com.at.service.impl;

import com.at.dao.TagDao;
import com.at.domain.Tag;
import com.at.exception.NotFoundException;
import com.at.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author : code1997
 * @date :2020-10-2020/10/8 19:20
 */
@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagDao tagDao;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagDao.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagDao.getOne(id);
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagDao.findAll(pageable);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Optional<Tag> byId = tagDao.findById(id);
        if (!byId.isPresent()){
            throw new NotFoundException("该标签不存在！更新失败！！！");
        }
        Tag tempTag = byId.get();
        BeanUtils.copyProperties(tag, tempTag);
        return tagDao.save(tempTag);
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size, sort);
        return tagDao.getTop(pageable);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagDao.deleteById(id);
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagDao.getTagByName(name);
    }

    @Override
    public List<Tag> listTag() {
        return tagDao.findAll();
    }

    /**
     * 未知正确性！！！
     * 可以实现功能再新增或者修改博客的页面进行标签的增加
     * @param ids ：id的集合
     * @return :返回指定的对象
     */
    @Override
    public List<Tag> listTag(String ids) {
        if (ids!=null&&ids.trim().length()>0){
            return tagDao.findAllById(()->Arrays.stream(ids.split(",")).map(Long::parseLong).iterator());
        }
        throw new NotFoundException("没找到");
    }
    /*private List<Long> converToList(String ids){

    }*/

}
